package com.seven.commons;

import java.sql.Timestamp;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @projectname:common-utils
 * @author: sevenDay
 * @date: 2019/8/9 21:56
 * @desc: 获取系统时间
 */
public enum SystemClock {

    INSTANCE(1);

    private final long period;

    private final AtomicLong now;

    private ScheduledExecutorService executorService;

    SystemClock(long period) {
        this.period = period;
        this.now = new AtomicLong(System.currentTimeMillis());
        scheduleClockUpdating();
    }


    public long currentTimeMillis() {
        return now.get();
    }

    public  String nowDate() {
        return new Timestamp(currentTimeMillis()).toString();
    }
    private void scheduleClockUpdating() {

        executorService = new ScheduledThreadPoolExecutor(1, new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
                Thread thread = new Thread(r, "System Clock");
                thread.setDaemon(true);
                return thread;
            }
        });
        executorService.scheduleAtFixedRate(() -> now.set(System.currentTimeMillis()), period, period, TimeUnit.MILLISECONDS);
        Runtime.getRuntime().addShutdownHook(new Thread(this::destroy));
    }
    public void destroy() {
        if (executorService != null) {
            executorService.shutdown();
        }
    }
}
